 <#import "inc/macro-page.html" as panel>
<#escape x as x?html>
<@panel.header "专业部门及班组缺冗员预警" "">
</@panel.header>
<@panel.body>
<!-- Bread crumb -->
<div class="row page-titles">
    <div class="col-md-5 align-self-center">
        <h3>专业部门及班组缺冗员预警</h3> </div>
    <div class="col-md-7 align-self-center">
        <div class="dropdown page-bar-drop-menu">
             <button class="btn btn-info dropdown-toggle clear-caret-down align-right" type="button" data-toggle="dropdown"><i class="fa fa-filter"></i></button>
             <div class="dropdown-menu filled-width">
                <#if list??>
       			<div class="page-search-box">
                 <form id="id-form-filter">
	              	<div class="row scroller-box">
	              	   <#list list as item>
	              		<div class="col-lg-6">
	              		   <input type="checkbox" class="check-filter" name="ids" value="${item.index!}"> ${item.name!}</input>
	              		</div>
	              		</#list>
	              	</div>
	              	<div class="button-list">	                         	   
	              		<button type="button" class="btn btn-danger btn-selected-clear"><i class="fa fa-trash"></i>&nbsp;清除</button>
	              		<button type="button" class="btn btn-info btn-selected-filter"><i class="fa fa-filter"></i>&nbsp;筛选分析</button>
	              	</div>
             	</form>
       			</div>      
             	</#if>
             </div>
         </div>                               
    </div>
</div>
<!-- End Bread crumb -->
<!-- Container fluid  -->
<div class="container-fluid">
    <!-- Start Page Content -->
    <div class="row">
        <div class="col-lg-12">
        	<div class="alert alert-info">
        		<ul class="text-list">
        			<li><span class="stat-outstanding-text"><b>绿色过载区</b></span>：配置率<0.8。代表人员配置较少，人均工作负荷繁重。</li>
        			<li><span class="stat-pass-text"><b>黄色良性区</b></span>：0.8<=配置率<1。代表人员配置适中，人均工作负荷适中。</li>
        			<li><span class="stat-bad-text"><b>红色轻载区</b></span>：1<=配置率<1.2。代表处于轻微超员状态。</li>
        			<li><span class="stat-inverse-text"><b>黑色警戒区</b></span>：配置率>1.2。代表冗员问题严重。</li>
        		</ul>                    	
        	</div>
        </div>
        <div class="col-lg-12">
            <div class="card">
				<div class="custom-card-header quick-bar">
					<div class="hint">&nbsp;</div>
					<button id="id-export-file" type="button" class="btn btn-dark btn-outline btn-sm" title="导出"><i class="fa fa-share-square-o"></i></button>
				</div>
                <div class="card-content p-t-20">
                    <div id="id-bar-chart" style="height: 460px"></div>
                    <div id="id-color-chart" style="height: 70px;"></div>
                </div>
            </div>
        </div>
    </div>
    <!-- End PAge Content -->
</div>
<!-- End Container fluid  -->
</@panel.body>
<@panel.footer>
<script type="text/javascript" src="${ROOT}/mind/js/lib/echart/echarts.min.5.4.0.js"></script>
<script type="text/javascript">
	// word导出事件
	document.getElementById('id-export-file').addEventListener('click', function() {
		// Ensure echarts charts have finished rendering
		setTimeout(() => {
			var charts = document.querySelectorAll('canvas');
			charts.forEach(chart => {
				var dataURL = chart.toDataURL();
				var imgTag = '<img src="' + dataURL + '" width="700" />';
				chart.insertAdjacentHTML('beforebegin', imgTag);
				chart.style.display = 'none'; // Hide the original canvas
			});

			// Create a temporary container for the export
			var exportContainer = document.createElement('div');
			exportContainer.id = 'export-container';
			exportContainer.style.width = '100%';

			var additionalContent = `
            <div class="alert alert-info">
                <ul class="text-list">
                    <li><span class="stat-outstanding-text"><b>绿色过载区</b></span>：配置率&lt;0.8。代表人员配置较少，人均工作负荷繁重。</li>
                    <li><span class="stat-pass-text"><b>黄色良性区</b></span>：0.8&lt;=配置率&lt;1。代表人员配置适中，人均工作负荷适中。</li>
                    <li><span class="stat-bad-text"><b>红色轻载区</b></span>：1&lt;=配置率&lt;1.2。代表处于轻微超员状态。</li>
                    <li><span class="stat-inverse-text"><b>黑色警戒区</b></span>：配置率&gt;1.2。代表冗员问题严重。</li>
                </ul>
            </div>
        `;
			exportContainer.insertAdjacentHTML('beforeend', additionalContent);
			// Clone ECharts charts
			var chartContainer = document.getElementById('id-bar-chart').cloneNode(true);
			exportContainer.appendChild(chartContainer);

			var chartContainers = document.getElementById('id-color-chart').cloneNode(true);
			exportContainer.appendChild(chartContainers);


// 			var clonedTable = document.getElementById('id-leader-table').cloneNode(true);
// // 直接添加内联样式到每个th和td元素
// 			clonedTable.querySelectorAll('th, td').forEach(function(cell) {
// 				cell.style.border = '1px solid #000';
// 				cell.style.borderCollapse = 'collapse'; // 注意：borderCollapse是CSS属性，不能作为内联样式设置，但这里为了示例而写
// 				cell.style.textAlign = 'center';
// 			});
// 			exportContainer.appendChild(clonedTable);



			// Convert the export container's HTML to a Word document
			var htmlHeader = `
          <!DOCTYPE html>
          <html>
          <head>
            <style>
               table, th, td {
                   border: 1px solid #000;
                   text-align: center;
                   border-collapse: collapse;
               }
               .stat-outstanding-text {color:#4CAF50;}
               .stat-pass-text {color: #ffa206;}
.stat-bad-text {color: #ef5350;}
.stat-inverse-text{color: #6a707e;}
            </style>
          </head>
          <body>`;
			var htmlFooter = `
          </body>
          </html>`;
			var htmlContent = htmlHeader + exportContainer.innerHTML + htmlFooter;

			var blob = new Blob([htmlContent], { type: 'application/msword' });
			var url = URL.createObjectURL(blob);
			var a = document.createElement('a');
			a.href = url;
			a.download = '专业部门及班组缺冗员预警.doc';
			a.click();
			URL.revokeObjectURL(url);

			// Clean up by removing the temporary container
			exportContainer.remove();

			// Revert changes made to the document for export
			charts.forEach(chart => {
				chart.previousSibling && chart.previousSibling.remove();
				chart.style.display = 'block'; // Restore the original canvas
			});
		}, 1000); // Adjust the timeout as needed to ensure charts have rendered
	});
$(document).ready(function(){
	const colorList = [
	  '#4caf50',
	  '#ffa206',
	  '#ef5350',
	  '#6a707e'
	];
    //先初始化图表实例
	var barChart = echarts.init(document.getElementById("id-bar-chart"), null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
    window.addEventListener('resize', barChart.resize);
    var colorChart = echarts.init(document.getElementById('id-color-chart'), null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
    window.addEventListener('resize', colorChart.resize);
    // 柱状图
    var initRainChart= function(combineData){	
    	
	    var option = {
	        color: ['#007470','#00c4c0'],
	        tooltip : {
	            trigger: 'axis'
	        },
	        legend: {
	            data:['用工数','定员数']
	        },
	        calculable : true,
	        xAxis : [
	            {
	                type : 'category',
	                data : combineData.nameArray,
	                axisLabel: {
	                	interval: 0
	                }
	            }
	        ],
	        yAxis : [
	            {
	                type : 'value'
	            }
	        ],
	        series : [
	            {
	                name:'用工数',
	                type:'bar',
	                label: {
	                	show: true,
	                	position: 'top'
	                },
	                data:combineData.factArray
	            },
	            {
	                name:'定员数',
	                type:'bar',
	                label: {
	                	show: true,
	                	position: 'top'
	                },
	                data:combineData.planArray
	            }
	        ]
	    };
	
	    if (option && typeof option === "object") {
	    	barChart.setOption(option, false);
	    }
    }
    
    var initCustomChart = function(combineData){
        
        const mydata = [];
        for(var i=0; i<combineData.nameArray.length; i++){
        	mydata.push({
        		value: [i*2,1,1.9,1, combineData.factArray[i], combineData.planArray[i], combineData.scoreArray[i],combineData.nameArray[i]],
        		itemStyle: {
        			color: combineData.colorArray[i]
        		}
        	})
        }
        	    
        var option = {
	      tooltip: {},
	      xAxis: {
	        scale: true,
	        show: false
	      },
	      yAxis: {
	    	  show: false
	      },
	      series: [
	        {
	          type: 'custom',
	          renderItem: function (params, api) {
	            var start = api.coord([api.value(0), api.value(1)]);
	            var size = api.size([api.value(2), api.value(3)]);
	            var style = api.style();
	            return {
	              type: 'rect',
	              shape: {
	                x: start[0],
	                y: start[1],
	                width: size[0],
	                height: size[1]
	              },
	              style: style
	            };
	          },
	          label: {
	            show: true,
	            left: 'center',
	            textStyle: {
	            	color: '#fff'
	            }
	          },
	          dimensions: ["","","","","用工数", "定员数", "配置率"],//对应数组中各个维度的显示值
	          encode: {
	            x: 0,
	            y: 6,
	            tooltip: [4, 5, 6],
	            itemName: 7
	          },
	          data: mydata
	        }
	      ]
	    };


        if (option && typeof option === 'object') {
        	colorChart.setOption(option);
        }
        
    }  
    
    var dataToChart = function(svrData) {
		var combineData = {
	        	 nameArray: [],
	        	 planArray: [],
	        	 factArray: [],
	        	 scoreArray:[],
	        	 colorArray: []
	    	};
		//获取选择框
		$('.check-filter').prop('checked', false);
		svrData.forEach(item=>{
			//转换数据
       		combineData.nameArray.push(item.name);
       		combineData.planArray.push(item.plan);
       		combineData.factArray.push(item.fact);
       		combineData.scoreArray.push(item.score);
       		var color = colorList[0]
       		if(item.score>1.2)
       			color = colorList[3];
       		else if(item.score>=1)
       			color = colorList[2];
       		else if(item.score>=0.8)
       			color: colorList[1]
       		combineData.colorArray.push(color);
       		//检查框
       		$('.check-filter').filter(function(){
       			return this.value === (item.index +'')
       		}).prop('checked', true);
       	});
    	
		return combineData;
    }

    //绑定事件
    $('.btn-selected-clear').click(function(){
    	$('.check-filter').prop('checked', false);
    });
    $(".btn-selected-filter").click(function(){
    	var selections = [];
    	$('.check-filter').filter(function(){
    		return $(this).prop('checked')==true;
    	}).each(item => {
    		selections.push(item);
    	})
    	$.post('${ROOT}/o/query', $('#id-form-filter').serialize(), function(data, status){
	    	if(data&& data.code === 'ok'){
	        	var mydata = dataToChart(data.data);
	    		initRainChart(mydata);
	    		initCustomChart(mydata);
	    		$('.dropdown-menu').removeClass("show");
	    	}else{
	    		toastr.error(data?data.desc:"提取数据失败，请确认是否已上传预警分析数据");
	    	}
	    }, 'json');
    });
    
    // $('#id-export-file').click(function(){
    // 	var pdfCanvas = $.fn.pdfcanvas({
    // 		title: '专业部门及班组缺冗员预警',
    // 		keywords: '单位和部门：；岗位类别：'
    // 	})
    //
    // 	pdfCanvas.addChart(document.querySelector("#id-bar-chart canvas"));
    // 	pdfCanvas.addChart(document.querySelector("#id-color-chart canvas"));
    // 	pdfCanvas.print();
    // });

    //先提取数据
    $.post('${ROOT}/o/list',function(data, status){
    	if(data&& data.code === 'ok'){
        	var mydata = dataToChart(data.data);
    		initRainChart(mydata);
    		initCustomChart(mydata);
    	}else{
    		toastr.error(data?data.desc:"提取数据失败，请确认是否已上传预警分析数据");
    	}
    }, 'json');
});
</script>
</@panel.footer>
</#escape>